package com.me.study.concurrent.threadPool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程工厂：可自定义线程名、线程池名字。类似还有：<p></p>
 *
 * 1，Spring 提供：<p>
 *      new CustomizableThreadFactory("springThread-pool-"); <p>
 * 2，commons-lang3 提供：<p>
 *      new BasicThreadFactory.Builder().namingPattern("lang3Thread-pool-").build(); <p>
 * 3，Google guava 提供：<p>
 *      new ThreadFactoryBuilder().setNameFormat("guavaThread-pool-").build();  <p>
 * 4，Jodd框架 jodd-core 提供：<p>
 *      new jodd.util.concurrent.ThreadFactoryBuilder().setNameFormat("joddThread-pool-").get();
 *
 *
 * @author ME
 * @date 2021/2/8
 */
public class NamedThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    NamedThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
